<template>
    <div>
        <el-dialog
            :visible.sync="engineVisible"
            :modal="false"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :fullscreen="true"
            :before-close="close"
        >
            <template slot="title">
                <div class="title-icon"></div>
                <span class="title-text" v-if="currentG6Node === '引擎运行中'">当日引擎运行状态更新记录</span>
                <span class="title-text" v-else>{{ currentG6Node }}结果</span>
            </template>
            <div style="overflow:hidden;margin-bottom:10px">
                <span v-if="currentG6Node !== '引擎运行中'" style="font-size: 14px;font-weight: 700;"
                    >{{ currentG6Node }}结果:
                    <b :class="getResultTypeColor(currentDetailMsg.resultType)">{{ resultTypeEnum[currentDetailMsg.resultType] }}</b>
                    &nbsp;&nbsp;&nbsp; {{ currentG6Node }}总量: <b class="blue">{{ currentDetailMsg.totalLoadSizeGB }}</b> &nbsp;&nbsp;&nbsp;
                    {{ currentG6Node }}总条数: <b class="blue">{{ currentDetailMsg.totalLoadAmount }}</b> 条</span
                >
                <!-- <div style="float:right" v-else>
                    <span>更新日期：</span>
                    <el-date-picker
                        v-model="dates"
                        type="daterange"
                        align="right"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        format="yyyy-MM-dd"
                        value-format="yyyyMMdd"
                        size="mini"
                        style="width:250px"
                        :clearable="false"
                        @change="getHistoryData"
                        :picker-options="setEndTime"
                    >
                    </el-date-picker>
                </div> -->
            </div>
            <vxe-table
                v-if="currentG6Node === '引擎运行中'"
                border
                :cell-style="getCellStyle"
                :row-config="{ isHover: true }"
                :sort-config="{
                    defaultSort: { field: sortProp, order: sortOrder, orders: ['desc', 'asc', null] },
                    remote: true,
                }"
                stripe
                :filter-config="{ remote: true }"
                @filter-change="handleFilter"
                @sort-change="handleSort"
                :data="tableData"
                show-header-overflow
                v-loading="loading"
                class="table"
                header-align="center"
                :key="columnsKey"
                ref="upstreamTable"
                auto-resize
                resizable
                :resizable-config="{ minWidth: '80' }"
            >
                <vxe-column
                    v-for="item in columns"
                    :field="item.val"
                    :title="item.name"
                    :key="item.val"
                    :filters="item.filters"
                    :min-width="item.minWidth || '90px'"
                    show-overflow="tooltip"
                    sortable
                >
                    <template #filter="{ $panel, column }" v-if="!checkFiltersParams.includes(item.val)">
                        <div>
                            <el-input
                                ref="searchInput"
                                class="my-input"
                                type="type"
                                v-for="(option, index) in column.filters"
                                :key="index"
                                v-model="option.data"
                                @input="$panel.changeOption($event, !!option.data, option)"
                            />
                        </div>
                    </template>
                    <template slot-scope="scope">
                        <span v-if="item.type == 'func'" :style="getStyle(item.val, scope.row[item.val])">
                            {{ item.funcBody(scope.row[item.val]) || '--' }}
                        </span>
                        <span v-else-if="item.type == 'func2'" :style="getStyle(item.val, scope.row[item.val])">
                            {{ item.funcBody(scope.row) || '--' }}
                        </span>
                        <span v-else>
                            {{ scope.row[item.val] === 0 || (scope.row[item.val] && (scope.row[item.val] + '').trim()) ? scope.row[item.val] : '--' }}
                        </span>
                    </template>
                </vxe-column>
            </vxe-table>
            <vxe-table
                v-else
                :data="tableData"
                ref="upstreamTable"
                :column-config="{ isHover: true }"
                :row-config="{ isHover: true }"
                :filter-config="{ remote: true }"
                :sort-config="{ defaultSort: { field: sortProp2, order: sortOrder2 }, orders: ['desc', 'asc', null], remote: true }"
                border
                show-header-overflow
                style="width: 100%"
                auto-resize
                @filter-change="handleFilter"
                @sort-change="handleSort"
                header-align="center"
                stripe
                resizable
                :resizable-config="{ minWidth: '80' }"
            >
                <vxe-column
                    field="tableName"
                    title="表名"
                    sortable
                    width="200"
                    :filters="[{ data: '' }]"
                    :filter-render="{ name: 'FilterInput' }"
                    show-overflow
                >
                    <template #filter="{ $panel, column }">
                        <el-input
                            class="my-input"
                            type="type"
                            v-for="(option, index) in column.filters"
                            :key="index"
                            v-model="option.data"
                            @input="$panel.changeOption($event, !!option.data, option)"
                        />
                    </template>
                </vxe-column>

                <vxe-column field="loadSizeMB" title="数据量加载(MB)" sortable show-overflow width="150" align="right"> </vxe-column>

                <vxe-column field="loadAmount" title="数据加载条数" sortable width="140" show-overflow align="right"> </vxe-column>

                <vxe-column field="finishTimes" title="加载时长(ms)" sortable width="150" show-overflow align="right"> </vxe-column>

                <vxe-column
                    field="resultType"
                    title="结果"
                    :filters="[
                        { label: '失败', value: '1' },
                        { label: '成功', value: '0' },
                    ]"
                    show-overflow
                    width="90"
                    sortable
                >
                    <template slot-scope="scope">
                        <span :style="getStyle('resultType', scope.row['resultType'])">
                            {{ resultTypeEnum[scope.row['resultType']] || '--' }}
                        </span>
                    </template>
                </vxe-column>
                <vxe-column
                    field="logInfo"
                    title="日志信息"
                    :filters="[{ data: '' }]"
                    :filter-render="{ name: 'FilterInput' }"
                    show-overflow
                    sortable
                >
                    <template #filter="{ $panel, column }">
                        <el-input
                            class="my-input"
                            type="type"
                            v-for="(option, index) in column.filters"
                            :key="index"
                            v-model="option.data"
                            @input="$panel.changeOption($event, !!option.data, option)"
                        />
                    </template>

                    <template slot-scope="scope">
                        <span>
                            {{ textFormat(scope.row['logInfo']) }}
                        </span>
                    </template>
                </vxe-column>
                <vxe-column field="loadDateTime" title="加载时间" show-overflow width="200" sortable align="center"> </vxe-column>
            </vxe-table>
            <RiskPagination :paging="paging" @page-change="getHistoryData"></RiskPagination>
        </el-dialog>
    </div>
</template>

<script lang="ts">
import RiskPagination from '@/common/components/risk-pagination.vue';
import RiskTable from '@/common/components/risk-table.vue';
import { dateFormat, timeFormat } from '@/utils/tools';
import { Vue, Component, Prop } from 'vue-property-decorator';
import XEUtils from 'xe-utils';

// 状态
const statusEnum: any = {
    '0': '连接正常',
    '1': '连接异常',
};

export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({
    name: 'UpstreamHistory',
    components: { RiskTable, RiskPagination },
})
export default class UpstreamHistory extends Vue {
    @Prop()
    engineVisible: boolean;
    @Prop() currentG6Node: string;
    @Prop() allCodeEnum: any;
    @Prop() currentDetailMsg: any;
    dateFormat = dateFormat;
    timeFormat = timeFormat;
    columnsKey: number = 1;

    private dates: any[] = [XEUtils.toDateString(new Date(), 'yyyyMMdd'), XEUtils.toDateString(new Date(), 'yyyyMMdd')];

    // 限制选择近1年内(365天)日期
    private setEndTime: any = {
        disabledDate: time => {
            const day = 360 * 24 * 3600 * 1000; // 31536000000
            // 返回小于当前日期并近一年内的日期
            return time.getTime() > Date.now() || time.getTime() < Date.now() - 8.64e7 - day;
        },
    };
    private updateNums: any = {
        CH: '1',
        HS: '2',
        HQ: '3',
        GZ25: '4',
    };

    private paging: pages = {
        total: 0,
        pageSize: 20,
        currentPage: 1,
    };

    // 实际排序参数字段
    sortEnum: any = {
        upstreamCode: 'C_UPSTREAM_CODE',
        oldStatus: 'C_OLD_STATUS',
        newStatus: 'C_NEW_STATUS',
        // '': 'D_UPDATE_DATE',
        updateTime: 'D_UPDATE_TIME',
    };
    sortEnum2: any = {
        tableName: 'C_TABLE_NAME',
        loadAmount: 'N_LOAD_AMOUNT',
        finishTimes: 'N_FINISH_TIMES',
        resultType: 'C_RESULT_TYPE',
        logInfo: 'C_LOG_INFO',
        loadDateTime: 'D_LOAD_DATE_TIME',
        loadSizeMB: 'N_LOAD_SIZE',
    };
    private sortProp: string = 'updateTime'; // 默认排序字段
    private sortOrder: string = 'desc'; // 默认排序方式
    private sortParam: string = 'D_UPDATE_TIME desc';

    private sortProp2: string = 'loadDateTime'; // 默认排序字段
    private sortOrder2: string = 'desc'; // 默认排序方式
    private sortParam2: string = 'D_LOAD_TIME desc';

    private checkFiltersParams: string[] = ['oldStatus', 'newStatus']; // 漏斗
    private searchParams: any = {
        upstreamCode: '',
        oldStatus: [],
        newStatus: [],
    };

    private searchParams2: any = {
        tableName: '',
        resultTypes: [],
        logInfo: '',
    };

    // 条目状态
    private columns: any[] = [
        // { name: '上游系统名称', val: 'upstreamCode', align: 'left', filters: [{ data: '' }] },
        {
            name: '原状态',
            val: 'oldStatus',
            align: 'center',
            filters: [
                { label: '连接正常', value: '0' },
                { label: '连接异常', value: '1' },
            ],
            type: 'func',
            funcBody: value => (value && value.trim() ? statusEnum[value] : '--'),
        },
        {
            name: '新状态',
            val: 'newStatus',
            align: 'center',
            filters: [
                { label: '连接正常', value: '0' },
                { label: '连接异常', value: '1' },
            ],
            type: 'func',
            funcBody: value => (value && value.trim() ? statusEnum[value] : '--'),
        },
        {
            name: '更新时间',
            val: 'updateTime',
            align: 'center',
            minWidth: '140px',
            type: 'func2',
            funcBody: value => this.handleDateAndTime(value),
        },
    ];

    tableData: any[] = [];
    loading: boolean = false;
    queryParams: any = {};
    private changeIconCols: any[] = [0]; // 第一列修改筛选图标  漏斗改放大镜

    private resultTypeEnum: any = {
        '0': '成功',
        '1': '失败',
        '2': '运行中',
    };
    mounted() {
        this.getHistoryData();
        // this.changeTable();
    }

    private getHistoryData() {
        const node = this.allCodeEnum.find(item => item.typeDes === this.currentG6Node);
        const searchParams = this.currentG6Node === '引擎运行中' ? this.searchParams : this.searchParams2;
        const sort = this.currentG6Node === '引擎运行中' ? this.sortParam : this.sortParam2;
        let startDate = Number(this.dates[0]) || null;
        let endDate = Number(this.dates[1]) || null;
        if (this.currentG6Node === '引擎运行中') {
            this.$axios({
                method: 'post',
                url: '/devopsmr/engine/status/history',
                data: { startDate, endDate, sort, paging: this.paging, ...searchParams },
            }).then((res: any) => {
                // res1.list.forEach(element => {
                //     element.updateTimeS = element.updateDate + element.updateTime;
                // });
                this.tableData = res.list;
                this.paging.total = res.total;
            });
        } else {
            this.$axios({
                method: 'post',
                url: '/devopsmr/node/result/detail',
                data: { nodeCode: node.typeCode, recordSource: node.recordSource, sort, paging: this.paging, ...searchParams },
            }).then((res: any) => {
                // res1.list.forEach(element => {
                //     element.updateTimeS = element.updateDate + element.updateTime;
                // });
                this.tableData = res.list;
                this.paging.total = res.total;
            });
        }
    }

    private handleSort(val): void {
        const { order, property } = val;
        this.sortParam = this.handleSortField(order, property);
        if (this.currentG6Node !== '引擎运行中') {
            this.sortParam2 = this.handleSortField(order, property);
        } else {
            this.sortParam = this.handleSortField(order, property);
        }
        this.getHistoryData();
    }

    private handleFilter({ field, values, datas }): void {
        if (this.currentG6Node !== '引擎运行中') {
            if (field === 'tableName' || field === 'logInfo') {
                this.searchParams2[field] = datas.join('');
            } else if (field === 'resultType') {
                this.searchParams2[field + 's'] = values;
            } else {
                this.searchParams2[field] = values;
            }
        } else {
            if (field === 'upstreamCode') {
                this.searchParams[field] = datas.join('');
            } else if (field === 'newStatus' || field === 'oldStatus') {
                this.searchParams[field + 'es'] = values;
            } else {
                this.searchParams[field] = values;
            }
        }

        this.getHistoryData();
    }

    // 获取排序字段
    handleSortField(name: string, order: string): string {
        let value = '';

        if (this.currentG6Node !== '引擎运行中') {
            if (name) {
                value = this.sortEnum2[order] + ' ' + name;
            }
        } else {
            if (name) {
                value = this.sortEnum[order] + ' ' + name;
            }
        }
        return value;
    }

    // 关闭窗口
    close() {
        this.$emit('close');
    }

    private getStyle(val: string, value: string): any {
        let color = '';
        if (['oldStatus', 'newStatus'].includes(val)) {
            color = value == '0' ? 'green' : value == '1' ? 'red' : '';
        }
        if (['resultType'].includes(val)) {
            color = value == '1' ? 'red' : value == '0' ? 'green' : '';
        }
        return { color: color };
    }

    handleDateAndTime(values) {
        let retValue = '--';
        if (values) {
            let date = String(values.updateDate);
            let time = String(values.updateTime);
            retValue = dateFormat(date) + '  ' + timeFormat(time);
        }
        return retValue;
    }

    private textFormat(val): string {
        if (!val.trim()) {
            return '--';
        }
        return val;
        // return val || '--';
    }

    getCellStyle({ column }) {
        let value = 'text-align:right';
        let obj = this.columns.find(item => item.val == column.property);
        if (obj) {
            value = 'text-align: ' + (obj.align || 'right');
        }
        return value;
    }

    // 改变筛选按钮
    changeTable() {
        const _this = this;
        this.$nextTick(() => {
            let iconDom = (_this.$refs['upstreamTable'] as any).$el.querySelectorAll('.vxe-icon--funnel');
            for (let i = 0; i < iconDom.length; i++) {
                if (this.changeIconCols.includes(i)) {
                    iconDom[i].className = 'vxe-filter--btn el-icon-search';
                }
            }
        });
    }

    private getResultTypeColor(val: string): string {
        let obj = {
            '0': 'green',
            '1': 'red',
            '2': 'blue',
        };
        return obj[val];
    }
}
</script>

<style lang="scss" scoped>
@import '@/pages/report/styles/common';

.title-icon {
    width: 20px;
    height: 20px;
    display: inline-block;
    border: 4px solid #2288ff;
    border-radius: 50%;
    margin-right: 4px;
}
.title-text {
    display: inline-block;
    font-weight: 900;
}
// /deep/ .el-dialog.is-fullscreen {
//     margin-top: 6vh;
// }
/deep/ .el-dialog {
    .el-dialog__header {
        display: flex;
        align-items: center;
        background-color: #fff;
        border-bottom: 1px solid #ccc;

        .el-dialog__title {
            font-size: 16px;
            color: #333333;
        }
        .el-dialog__headerbtn .el-dialog__close {
            font-size: 24px;
            color: #515151;
        }
    }
    .el-dialog__body {
        max-height: 100%;
    }
}
/deep/ .el-dialog__wrapper {
    overflow: hidden;
}
/deep/ .vxe-table .vxe-table--body-wrapper.body--wrapper {
    height: calc(94vh - 175px);
}
.table /deep/ .vxe-cell .vxe-cell--title {
    font-size: 14px;
}

/deep/ .el-date-editor .el-range-separator {
    padding: 0;
}

.green {
    color: rgb(135, 208, 104);
}

.blue {
    color: #107fff;
}

.red {
    color: red;
}
</style>
